<template>
	<div class="page">
		<div class="page-header">
			<h1 class="page-title">社会服务管理</h1>
			<p class="page-subtitle">审核教职工提交的社会服务信息，按条件统计</p>
		</div>

		<el-card class="mb16">
			<el-form :inline="true" :model="query" label-width="80px">
				<el-form-item label="类型">
					<el-select v-model="query.type" clearable placeholder="全部" style="width: 180px">
						<el-option label="政府顾问" value="政府顾问" />
						<el-option label="企业咨询专家" value="企业咨询专家" />
						<el-option label="评审专家" value="评审专家" />
						<el-option label="公共政策" value="公共政策" />
						<el-option label="调研报告" value="调研报告" />
						<el-option label="公益活动" value="公益活动" />
					</el-select>
				</el-form-item>
				<el-form-item label="级别">
					<el-select v-model="query.level" clearable placeholder="全部" style="width: 140px">
						<el-option label="校级" value="校级" />
						<el-option label="市级" value="市级" />
						<el-option label="省级" value="省级" />
						<el-option label="国家级" value="国家级" />
						<el-option label="国际级" value="国际级" />
					</el-select>
				</el-form-item>
				<el-form-item label="年份">
					<el-input v-model.number="query.year" placeholder="全部" style="width: 120px" />
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="query.status" clearable placeholder="全部" style="width: 140px">
						<el-option label="待审核" value="PENDING" />
						<el-option label="已通过" value="APPROVED" />
						<el-option label="已驳回" value="REJECTED" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">查询</el-button>
					<el-button @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="userName" label="教师" width="120" />
				<el-table-column prop="serviceType" label="类型" width="160" />
				<el-table-column prop="title" label="标题/角色" min-width="200" show-overflow-tooltip />
				<el-table-column prop="organizationName" label="单位" min-width="200" show-overflow-tooltip />
				<el-table-column prop="level" label="级别" width="100" />
				<el-table-column prop="year" label="年份" width="90" />
				<el-table-column prop="status" label="状态" width="110">
					<template #default="{ row }">
						<el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="340" fixed="right">
					<template #default="{ row }">
						<el-button size="small" @click="handleView(row)">查看</el-button>
						<el-button size="small" type="primary" @click="openAttachments(row)">附件</el-button>
						<el-button size="small" type="success" :disabled="row.status!=='PENDING'" @click="handleReview(row, 'APPROVED')">通过</el-button>
						<el-button size="small" type="danger" :disabled="row.status!=='PENDING'" @click="handleReview(row, 'REJECTED')">驳回</el-button>
					</template>
				</el-table-column>
			</el-table>

			<div style="margin-top: 16px; display: flex; justify-content: flex-end;">
				<el-pagination
					background
					layout="prev, pager, next, jumper, ->, total"
					:total="total"
					:page-size="size"
					:current-page="page"
					@current-change="handlePageChange"
				/>
			</div>
		</el-card>

		<el-dialog v-model="showView" title="查看社会服务" width="600px">
			<el-descriptions :column="1" border>
				<el-descriptions-item label="教师">{{ currentRow?.userName }}</el-descriptions-item>
				<el-descriptions-item label="类型">{{ currentRow?.serviceType }}</el-descriptions-item>
				<el-descriptions-item label="标题/角色">{{ currentRow?.title }}</el-descriptions-item>
				<el-descriptions-item label="单位">{{ currentRow?.organizationName }}</el-descriptions-item>
				<el-descriptions-item label="级别">{{ currentRow?.level || '-' }}</el-descriptions-item>
				<el-descriptions-item label="起止">{{ currentRow?.startDate }} ~ {{ currentRow?.endDate || '-' }}</el-descriptions-item>
				<el-descriptions-item label="状态">{{ statusText(currentRow?.status) }}</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<el-button @click="showView = false">关闭</el-button>
			</template>
		</el-dialog>

		<el-dialog v-model="showAttach" title="附件管理" width="680px">
			<el-table :data="attachList" size="small">
				<el-table-column prop="fileName" label="文件名" min-width="280" show-overflow-tooltip />
				<el-table-column label="操作" width="200">
					<template #default="{ row }">
						<el-button size="small" @click="downloadAttachment(row)">下载</el-button>
						<el-button size="small" type="danger" @click="deleteAttachment(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<template #footer>
				<el-button @click="showAttach = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { socialServiceApi } from '@/api/academicSocial'

const query = reactive({ type: '', level: '', year: '', status: '' })
const tableData = ref([])
const showView = ref(false)
const showAttach = ref(false)
const attachList = ref([])
const currentRow = ref(null)

// 分页
const page = ref(1)
const size = ref(10)
const total = ref(0)

const statusTag = (s) => ({ 'PENDING': 'warning', 'APPROVED': 'success', 'REJECTED': 'danger' }[s] || 'info')
const statusText = (s) => ({ 'PENDING': '待审核', 'APPROVED': '已通过', 'REJECTED': '已驳回' }[s] || s)

const parsePageResult = (res) => {
	const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : (Array.isArray(res?.list) ? res.list : []))
	tableData.value = list
	total.value = (typeof res?.total === 'number') ? res.total : (typeof res?.data?.total === 'number' ? res.data.total : list.length)
}

const loadTable = async () => {
	const res = await socialServiceApi.listAll({ ...query, page: page.value, size: size.value })
	parsePageResult(res)
}

const handleSearch = () => { page.value = 1; loadTable() }
const resetQuery = () => { Object.assign(query, { type: '', level: '', year: '', status: '' }); page.value = 1; loadTable() }
const handlePageChange = (p) => { page.value = p; loadTable() }

const handleView = (row) => { currentRow.value = row; showView.value = true }

const handleReview = async (row, action) => {
	try {
		const text = action === 'APPROVED' ? '通过该记录' : '驳回该记录'
		await ElMessageBox.confirm(`确认${text}吗？`, '审核确认', { type: 'warning' })
		await socialServiceApi.review(row.id, { action })
		ElMessage.success('操作成功')
		await loadTable()
	} catch (e) {
		if (e !== 'cancel') ElMessage.error(e?.response?.data || e?.message || '操作失败')
	}
}

const openAttachments = async (row) => {
	currentRow.value = row
	const res = await socialServiceApi.listAttachments(row.id)
	attachList.value = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
	showAttach.value = true
}

const downloadBlob = (blob, filename) => {
	const url = window.URL.createObjectURL(blob)
	const a = document.createElement('a')
	a.href = url
	a.download = filename || 'download'
	document.body.appendChild(a)
	a.click()
	window.URL.revokeObjectURL(url)
	document.body.removeChild(a)
}

const downloadAttachment = async (row) => {
	const resp = await socialServiceApi.downloadAttachment(currentRow.value.id, row.id)
	const blob = resp?.data || resp
	downloadBlob(blob, row.fileName)
}

const deleteAttachment = async (row) => {
	await ElMessageBox.confirm('确定删除该附件吗？', '删除确认', { type: 'warning' })
	await socialServiceApi.deleteAttachment(currentRow.value.id, row.id)
	ElMessage.success('已删除')
	await openAttachments(currentRow.value)
}

loadTable()
</script>

<style scoped>
.mb16 { margin-bottom: 16px; }
.page-header { margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; }
.page-subtitle { margin: 4px 0 0 0; color: #666; }
</style> 